const ExcelJS = require('exceljs');
const childProcess = require('child_process');
const { log, time } = require('console');

const ERROR_CODE = -1;
const getPidCommand = "hdc shell pidof pasteboard_service";
const getDumperCommand = pid => `hdc shell hidumper --mem-smaps ${pid} -v`
const EXCEL_NAME = "pasteboard_service_mem"


const table_header = [
    "Size", "Rss", "Pss", "Shared Clean", "Shared Dirty", "Private Clean",
    "Private Dirty", "Swap", "SwapPss", "perm", "start", "End", "Name"
]


const genExcelName = () => {
    const now = new Date();
    return `${EXCEL_NAME}_${now.getTime()}.xlsx`;
}

const getPasteBoardPid = () => {
    try {
        const output = childProcess.execSync(getPidCommand)
        return output.toString().trim();
    } catch(err) {
        console.log(err);
        return ERROR_CODE;
    }
}


async function readColumnFromExcel(filePath, columnLetter) {
    let workbook = new ExcelJS.Workbook();
    await workbook.xlsx.readFile(filePath);
    let worksheet = workbook.getWorksheet(1); // 或者使用 workbook.getWorksheet('Sheet1') 指定工作表名
    let columnData = worksheet.getColumn(columnLetter); // 获取指定列的数据
 
    // 提取列中的所有值
    let values = columnData.values.map(value => value ? value.toString() : null);
    return values;
}

let excelName = '';

const getDumperData = async () => {
    const pid = getPasteBoardPid();
    log(`剪贴板pid: ${pid}`)
    try {
        let dumperCmd = getDumperCommand(pid);
        log(dumperCmd);
        const buf  = childProcess.execSync(getDumperCommand(pid));
        let lines = buf.toString().split('\n').slice(5);
        let _ = lines.pop();
        let summaryLine = lines.pop();
        // 创建一个新的工作簿
        const workbook = new ExcelJS.Workbook();
        // 添加一个工作表
        const worksheet = workbook.addWorksheet('Sheet 1');
        // 添加数据
        worksheet.addRow(table_header);
        // 打印总数据
        log(summaryLine);
        let summaryLineArr = summaryLine.split(/\s+/) 
        let pssTotal = summaryLineArr[2];
        worksheet.addRow(summaryLineArr);
        lines.forEach(line => {
            let memData = line.split(/\s+/).map(v => {
                let ret = Number(v);
                return isNaN(ret) ? v : ret;
            });
            memData.pop();
            worksheet.addRow(memData);
        });
        log(`pss Total: ${pssTotal}`);
        // 保存工作簿到文件
        excelName = genExcelName();
        workbook.xlsx.writeFile(excelName).then(() => {
            console.log('工作簿已保存: ' + " " + excelName);
        }).catch((err) => {
            console.error('保存工作簿时出错', err);
        });
        lines = lines.slice(4);
    } catch (err) {
        console.log(err);
    }
}


(async () => {

    await getDumperData();

    // let filePath = './hdc_reboot_copy_5min.xlsx'; // Excel文件路径
    // let columnLetter = 'M'; // 例如，读取第一列（A列）
    // // 黄区数据
    // let data = await readColumnFromExcel(filePath, columnLetter);
    // data = Array.from(new Set(data));
    // data = data.filter(d => (d !== undefined && d.endsWith('.so'))).map(d => d.split('/').pop().trim());

    // // let filePath2 = './pasteboard_service_mem_1738828113364.xlsx';

    // let data2 = await readColumnFromExcel(excelName, columnLetter);
    // data2 = Array.from(new Set(data2));
    // data2 = data2.filter(d => (d !== undefined && d.endsWith('.so'))).map(d => d.split('/').pop().trim());
    // // log(data2);

    // // 蓝区数据
    // // 对比数据内数据
    // const added = Array.from(new Set(data2.filter(item => !data.includes(item)) ));
    // log(added)
    // log('lib diff count: ' + added.length)

})();

